#include <stdint.h>
#include <stdio.h>

#include "py/obj.h"
#include "py/gc.h"
#include "py/runtime.h"
#include "mphalport.h"

#include "mod/machine.h"


STATIC mp_obj_t machine_timer_start(mp_obj_t self_in);


STATIC void machine_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    machine_timer_obj_t *self = self_in;

    mp_printf(print, "Timer(%d, mode=%s, period=%u(%s)) ", 
        (self->htim.Instance), 
        ((self->htim.Init.AutoReload == TIM_AUTORELOAD_PRELOAD_ENABLE) ? ("reload") : ("oneshot")),
        (self->htim.Init.Period),
        ((self->htim.Init.Unit == TIM_UNIT_US) ? ("us") : ("ms")));
}

STATIC mp_obj_t machine_timer_init_helper(machine_timer_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {

    enum { ARG_mode, ARG_period, ARG_unit, ARG_callback};
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_mode,         MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_AUTORELOAD_PRELOAD_ENABLE} },
        { MP_QSTR_period,       MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
        { MP_QSTR_unit,         MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_UNIT_US} },
        { MP_QSTR_callback,     MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    };

    // Parse args
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);

    self->htim.Instance = self->timer_id;                  // TIM0 ~ TIM5
    self->htim.Init.Unit = args[ARG_unit].u_int;           // TIM_UNIT_US(0), TIM_UNIT_MS(1)
    self->htim.Init.Period = args[ARG_period].u_int;       // period
    self->htim.Init.AutoReload = args[ARG_mode].u_int;     // TIM_AUTORELOAD_PRELOAD_[ENABLE, DIASBLE]
    // 设置回调函数
    self->callback = (args[ARG_callback].u_obj == MP_OBJ_NULL) ? (mp_const_none) : (args[ARG_callback].u_obj);
    // 初始化定时器
    HAL_TIM_Base_Init(&self->htim);
    // 启动定时器
    //machine_timer_start(MP_OBJ_FROM_PTR(self));
    return mp_const_none;
}

STATIC mp_obj_t machine_timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
    
    machine_timer_obj_t* self;
    // timer id
	int timer_id = mp_obj_get_int(args[0]);
	if (timer_id < 0 || timer_id > MICROPY_HW_MAX_TIMER_CNT) {
		mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("Timer(%d) doesn't exist"), timer_id);
    }
    // alloc memory
    if (MP_STATE_PORT(timer_obj_all)[timer_id] == NULL) {	
        self = m_new0(machine_timer_obj_t, 1);
        self->base.type = &machine_timer_type;
        self->timer_id = timer_id;
         self->callback = mp_const_none;
        MP_STATE_PORT(timer_obj_all)[timer_id] = self;
    } else {
        // reference existing UART object
        self = MP_STATE_PORT(timer_obj_all)[timer_id];
    }
    if (n_args > 1 || n_kw > 0) {
        // start the peripheral
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
        machine_timer_init_helper(self, n_args - 1, args + 1, &kw_args);
    }
    return MP_OBJ_FROM_PTR(self);
}

STATIC mp_obj_t machine_timer_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    machine_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);
    return machine_timer_init_helper(self, n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_timer_init_obj, 1, machine_timer_init);

STATIC mp_obj_t machine_timer_deinit(mp_obj_t self_in) {
    machine_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    HAL_TIM_Base_Stop_IT(&self->htim);
    self->is_enabled = false;
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_timer_deinit_obj, machine_timer_deinit);

STATIC mp_obj_t machine_timer_start(mp_obj_t self_in) {
    machine_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    self->is_enabled = true;
    HAL_TIM_Base_Start_IT(&self->htim);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_timer_start_obj, machine_timer_start);

STATIC mp_obj_t machine_timer_stop(mp_obj_t self_in) {
    machine_timer_deinit(self_in);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_timer_stop_obj, machine_timer_stop);

// 设置回调函数
STATIC mp_obj_t machine_timer_callback(size_t n_args, const mp_obj_t* args)
{
    machine_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);    
    if(n_args == 1){
        return self->callback;
    }else{
        self->callback = args[1];
    }
    return mp_const_none;
}

STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_timer_callback_obj, 1, 2, machine_timer_callback);

STATIC const mp_rom_map_elem_t machine_timer_locals_dict_table[] = {
    // 定时器初始化
    { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_timer_init_obj) },
    { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_timer_deinit_obj) },
    // 启动、暂停定时器
    { MP_ROM_QSTR(MP_QSTR_start), MP_ROM_PTR(&machine_timer_start_obj) },
    { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&machine_timer_stop_obj) },
    // 单位
    { MP_ROM_QSTR(MP_QSTR_UNIT_MS), MP_ROM_INT(TIM_UNIT_MS) },
    { MP_ROM_QSTR(MP_QSTR_UNIT_US), MP_ROM_INT(TIM_UNIT_US) },
    // 周期
    { MP_ROM_QSTR(MP_QSTR_MODE_ONESHOT), MP_ROM_INT(TIM_AUTORELOAD_PRELOAD_DISABLE) },
    { MP_ROM_QSTR(MP_QSTR_MODE_PRELOAD), MP_ROM_INT(TIM_AUTORELOAD_PRELOAD_ENABLE) },
    // 回调
    {MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&machine_timer_callback_obj) },
    
};
STATIC MP_DEFINE_CONST_DICT(machine_timer_locals_dict, machine_timer_locals_dict_table);

const mp_obj_type_t machine_timer_type = {
    { &mp_type_type },
    .name = MP_QSTR_Timer,
    .print = machine_timer_print,
    .make_new = machine_timer_make_new,
    .locals_dict = (mp_obj_dict_t *)&machine_timer_locals_dict,
};
